package com.jinhua.config;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理
 */
@Slf4j
public class MyExceptionHandler implements HandlerExceptionResolver {

	public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
		ModelAndView mv = new ModelAndView();
		FastJsonJsonView view = new FastJsonJsonView();
		Map<String, Object> attributes = new HashMap<String, Object>();
		if (ex instanceof MyException) {
			attributes.put("code", ((MyException) ex).getCode());
			attributes.put("msg", ex.getMessage());
			view.setAttributesMap(attributes);
			mv.setView(view);
			return mv;
		}
//		else if (ex instanceof UnauthenticatedException) {
//			log.warn("shiro---token错误");
//			attributes.put("code", 10001);
//			attributes.put("msg", "token错误");
//			view.setAttributesMap(attributes);
//			mv.setView(view);
//			return mv;
//		} else if (ex instanceof UnauthorizedException) {
//			log.warn("shiro---用户无权限");
//			attributes.put("code", 10002);
//			attributes.put("msg", "用户无权限");
//			view.setAttributesMap(attributes);
//			mv.setView(view);
//			return mv;
//		}
		else {
			attributes.put("code", 500);
			attributes.put("msg", ex.getMessage());
		}
		view.setAttributesMap(attributes);
		mv.setView(view);
		return mv;
	}
}


